<template>
  <view class="address-form">
    <form>
        <view v-if="this.isEditMode===true" class="form-item">
            <label>ID</label>
            <input v-model="form.id" id="id" type="text" disabled required/>
        </view>
		<view class="form-item">
		  <label>单位名称</label>
		  <wd-picker placeholder="请选择单位" custom-class="wd-picker__field" :columns="columns" v-model="form.clientId" />
		</view>
      <view class="form-item">
        <label>地址名称</label>
        <input v-model="form.addrName" id="addrName" type="text" placeholder="请输入地址名称" required />
      </view>

      <view class="form-item">
        <label>详细地址</label>
		<view class="input-wrapper">
		  <input v-model="form.address" id="address" type="text" placeholder="等待获取详细地址" required class="readonly-field" />
		  <wd-icon :class="{'readonly-button':!editLocation}" name="refresh" size="22px" @click="getLatitude()"></wd-icon>
		</view>
      </view>
      <!-- 经度和纬度字段设置为只读，且不可点击 -->
      <view class="form-item">
        <label>纬度</label>
        <input v-model="form.latitude" id="latitude" type="text" placeholder="等待获取纬度" class="readonly-field" />
      </view>

      <view class="form-item">
        <label>经度</label>
        <input v-model="form.longitude" id="longitude" type="text" placeholder="等待获取经度" class="readonly-field" />
      </view>

      <view class="form-item">
        <label>二维码</label>
          <UploadImage :limit=1 :uploadedImages="addrCodeList" :uploadUrl="this.$baseUrl+'/api/files/upload'">
          </UploadImage>
      </view>
      <button type="primary" @click="submitAddress()">{{ isEditMode ? '更新' : '新增' }}地址</button>
      <button v-if="isEditMode" style="margin-top: 15px" type="primary" @click="qrcodeScan(form.id)">生成二维码</button>
      <button v-if="isEditMode" style="margin-top: 15px" type="primary" @click="downloadQrcode(form.addrCode)">下载二维码</button>
    </form>
  </view>
</template>

<script>
	import { getLocation } from '../../common/globleJS/globle'
    import request from '../../util/request'
    import UploadImage from '@/common/component/UploadImage.vue';
	export default {
        components: {
            UploadImage
        },
		onLoad(options) {
			this.getClients()
			// 编辑
			if(options.data!==undefined){
				this.isEditMode=true
				this.editLocation=false // 编辑模式下默认不允许修改位置
				var data = JSON.parse(options.data)
				this.form=data
                this.form.addrCode="/api/file/download/" + this.form.addrCode
				this.updateAddr(data)
			}else{
				// 获取位置信息
				this.getLatitude()
				this.editLocation=true
				this.isEditMode=false
			}
		},
        mounted() {
            this.initPhotoList()
        },
		data() {
			return {
				editLocation: false,
				isEditMode: false, // 判断是否为编辑模式
				form:{},
				columns:[],
                addrCodeList:[],
			}
		},
		methods: {
            downloadQrcode (addrCode) {
                // 假设你有一个网络图片的链接
                let imageUrl = this.$baseUrl + '/api/files/codeDownload/' + addrCode.substring(addrCode.lastIndexOf("/") + 1);
                // 下载图片
                uni.downloadFile({
                    url: imageUrl,
                    success: downloadResult => {
                        if (downloadResult.statusCode === 200) {
                            // 下载成功，保存图片到系统相册
                            uni.saveImageToPhotosAlbum({
                                filePath: downloadResult.tempFilePath,
                                success: () => {
                                    uni.showToast({
                                        title: '图片保存成功'
                                    });
                                },
                                fail: () => {
                                    uni.showToast({
                                        title: '图片保存失败',
                                        icon: 'none'
                                    });
                                }
                            });
                        } else {
                            uni.showToast({
                                title: '图片下载失败',
                                icon: 'none'
                            });
                        }
                    },
                    fail: () => {
                        uni.showToast({
                            title: '图片下载失败',
                            icon: 'none'
                        });
                    }
                });
            },
            qrcodeScan (id) {
                request.get("/qrCode/generator?content=" + "http://124.167.249.190:9290/addrCode?id=" + id +"&id="+id).then(res => {
                        if (res.code === '200') {
                            uni.showToast({ title: '生成成功', icon: 'success' });
                        } else {
                            uni.showToast({ title: '生成失败', icon: 'error' });
                        }
                    })
            },
            initPhotoList() {
                this.addrCodeList = this.form.addrCode ? this.form.addrCode.split(',').map(url => {
                    return {url}
                }) : [];
            },
            handlePhoto() {
                this.addrCodeList.forEach((item,index)=>{
                    if(index==0){
                        this.form.addrCode=item.url.replace("/api/file/download/", "")
                    }else{
                        this.form.addrCode+=","+item.url.replace("/api/file/download/", "")
                    }
                })
            },
			async updateAddr(data){
				// 判断是否有地址数据
				console.log("判断地址是否能更新")
				if(data.address==null||data.latitude==null||data.longitude==null){
					this.editLocation=true
					// this.getLatitude()
				}else{
					// 判断距离是否超过预设距离，未超过才可进行更新地址信息
					const oldLatitude = data.latitude
					const oldLongitude = data.longitude
					let position = await getLocation()
					const nowLatitude = position.latitude
					const nowLongitude = position.longitude
					const distance = this.getDistance(oldLatitude, oldLongitude, nowLatitude, nowLongitude);
					if (distance > 100) {
						console.log("距离超过100米");
					} else {
						console.log("距离未超过100米");
						// 这里可以进行更新地址信息的操作
						this.editLocation=true
					}
				}
			},
			getDistance(lat1, lon1, lat2, lon2) {
			    const rad = Math.PI / 180;
				console.log(rad)
			    const earthRadius = 6371e3; // 地球半径，单位为米

			    const φ1 = lat1 * rad;
			    const φ2 = lat2 * rad;
			    const Δφ = (lat2 - lat1) * rad;
			    const Δλ = (lon2 - lon1) * rad;

			    const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
			              Math.cos(φ1) * Math.cos(φ2) *
			              Math.sin(Δλ / 2) * Math.sin(Δλ / 2);

			    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				console.log("距离：")
				console.log(earthRadius * c)
			    return earthRadius * c; // 返回距离，单位为米
			},
			async getLatitude() {
			  let position = await getLocation()
			  console.log(position)
			  this.form.latitude = position.latitude
			  this.form.longitude = position.longitude
			  const addr = position.address
			  this.form.address = addr.province + addr.city + addr.district + addr.street + addr.streetNum + addr.poiName
			},
			getClients(){
				request.get("/user/getClient?userId="+this.$store.state.userInfo.id).then(res=>{
					this.columns=res.data
				})
			},
			submitAddress() {
              this.handlePhoto()
			  // 地址的 API 调用
			  console.log("新增地址:", this.form);
			  // 执行 API 请求等操作
			  request.post("/inspect-addr-code/edit",this.form)
			}
		}
	}
</script>

<style scoped>
.address-form {
  padding: 20px;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #333;
}
.input-wrapper {
  display: flex;
  align-items: center; /* 使输入框和按钮垂直居中对齐 */
  gap: 10px; /* 输入框和按钮之间的间隔 */
}

.get-addr-button{
	width: 15%;
	margin-right: 20px;
	height: 40px;
	font-size: 15px;
}

.form-item input {
  width: 90%;
  padding: 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
  font-size: 14px;
}

.readonly-field {
  background-color: #ebebeb; /* 只读字段背景色，提示用户不能修改 */
  pointer-events: none; /* 禁用点击事件 */
  cursor: not-allowed; /* 设置不可点击的光标样式 */
}

.readonly-button {
	color: #ccc;
	pointer-events: none; /* 禁用点击事件 */
	cursor: not-allowed; /* 设置不可点击的光标样式 */
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(45deg, #aaffff, #e65c5c); /* 渐变背景 */
  color: white;
  border: none;
  border-radius: 8px; /* 圆角效果 */
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s ease, transform 0.3s ease; /* 按钮点击效果 */
}

.submit-btn:hover {
  background: linear-gradient(45deg, #e65c5c, #f76c6c); /* 悬停时改变背景渐变方向 */
  transform: scale(1.05); /* 放大效果 */
}

.submit-btn:active {
  transform: scale(0.98); /* 按下时轻微缩小效果 */
}

:deep(.wd-picker__cell){
	width: 90%;
	background-color: transparent;
	border: 1px solid #ccc; /* 设置边框 */
	border-radius: 5px;      /* 圆角效果 */
	padding: 10px;           /* 内边距 */
	font-size: 14px;         /* 字体大小 */
}
:deep(.wd-picker__placeholder){
	color: gray;
}

.upload-image-container {
    display: flex;
    flex-direction: column;
}

.image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    justify-content: flex-start; /* 左对齐 */
}

.image-item {
    position: relative;
    width: 75px; /* 每张图片占用的空间 */
    height: 75px;
    overflow: hidden;
    border-radius: 8px;
    background-color: #f5f5f5; /* 统一的背景色 */
}

.image-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
    border: 2px solid #ddd; /* 边框样式 */
}

.placeholder {
    width: 75px; /* 每张图片占用的空间 */
    height: 75px;
    display: flex;
    flex-direction: column; /* 使图标和文本垂直排列 */
    align-items: center;
    justify-content: center;
    border: 2px dashed #ccc;
    border-radius: 8px;
    background-color: #f5f5f5;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.placeholder:hover {
    background-color: #e1e1e1; /* 悬浮时改变背景色 */
}

.placeholder-text {
    color: #aaa;
}

.count {
    font-size: 12px;
    color: #666;
    margin-top: 4px; /* 给文本添加一些间距 */
}


.delete-btn {
    position: absolute;
    top: -5px; /* 删除按钮离图片的顶部稍微偏移 */
    right: -5px; /* 删除按钮离图片的右边稍微偏移 */
    background-color: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    padding: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.delete-btn:hover {
    background-color: rgba(0, 0, 0, 0.8); /* 悬浮时改变背景色 */
}

.delete-text {
    color: white;
    font-size: 16px;
}

.delete-btn:active {
    transform: scale(0.9); /* 点击删除按钮时缩小 */
}
</style>
